package org.example.framework.protocol.http;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import java.util.Objects;

/**
 * @author shenguangyang
 */
public class HttpServer {
    public void start(String hostname, Integer port) {
        try {
            long start = System.currentTimeMillis();
            Tomcat tomcat = new Tomcat();
            tomcat.setHostname(hostname);
            tomcat.setPort(port);

            //需要设置一下端口，不然无法访问
            tomcat.getConnector().setPort(port);

            //创建一个context
            tomcat.addContext("/", Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getFile());
            tomcat.addServlet("/", "hello", new DispatcherServlet()).addMapping("/");
            // 启动tomcat
            tomcat.start();
            long end = System.currentTimeMillis();
            System.out.println("启动完成,共使用了:" + (end - start) + "ms");
            // 进入监听状态,如果不进入监听状态,启动tomat后就会关闭tomcat
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }
}
